package com.fujimana.rockincat.restree.init.converter;

import com.fujimana.rockincat.restree.annotation.mime.MimeType;
import com.fujimana.rockincat.restree.converter.Converter;
import com.fujimana.rockincat.restree.init.Handler;
import com.fujimana.rockincat.restree.init.Item;
import com.fujimana.rockincat.restree.util.ClassUtils;

public class ConverterHandler implements Handler<Item> {

	@SuppressWarnings("unchecked")
	@Override
	public Item handle(String resource) {
		Class<? extends Converter> clazz = (Class<? extends Converter>) ClassUtils.loadClass(resource);
		
		MimeType m = clazz.getAnnotation(MimeType.class);
		
		return new ConverterItem(m.type(), clazz);
	}

	@Override
	public boolean isHandle(String resource) {
		
		if (!resource.endsWith(".class")) {
			return false;
		}
		
		Class<?> clazz = ClassUtils.loadClass(resource);
		
		if(clazz == null) {
			return false;
		}
		
		if(Converter.class.isAssignableFrom(clazz) == false) {
			return false;
		}

		return clazz.getAnnotation(MimeType.class) != null;
	}

}
